package gejw.android.wifimandatoryconnection.Wifi.Listener;

import gejw.android.wifimandatoryconnection.Wifi.Utils.WifiUtils;
import gejw.android.wifimandatoryconnection.Wifi.Utils.WifiUtils.WifiState;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class WifiListener {

	public interface WifiChangeCallBack {
		public void WifiChanged();

		public void WifiChanged(String ssid);

		public void WifiStateChanged(WifiState state);
	}

	private static WifiListener ssidListener = null;

	public static WifiListener getInstance(Context context) {
		if (ssidListener == null)
			ssidListener = new WifiListener(context);
		return ssidListener;
	}

	private Context mContext;
	private WifiChangeCallBack mWifiChangeCallBack;
	private WifiInfo mWifiInfo;
	private String SSID;
	private boolean isStartListener = false;

	public WifiListener(Context context) {
		mContext = context;
	}

	public WifiListener setmWifiChangeCallBack(
			WifiChangeCallBack mWifiChangeCallBack) {
		this.mWifiChangeCallBack = mWifiChangeCallBack;
		return ssidListener;
	}

	/**
	 * 开始监听wifi
	 */
	public void start() {
		if (isStartListener)
			return;
		IntentFilter filter = new IntentFilter();
		filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		mContext.registerReceiver(receiver, filter);
		isStartListener = true;
	}

	/**
	 * 停止监听wifi
	 */
	public void stop() {
		try {
			mContext.unregisterReceiver(receiver);
			isStartListener = false;
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// wifi变化
			WifiManager wifiManager = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			mWifiInfo = wifiManager.getConnectionInfo();
			SSID = mWifiInfo.getSSID();
			if (mWifiChangeCallBack != null) {
				// 获取wifi状态
				WifiState wifistate = WifiUtils.State2State(wifiManager
						.getWifiState());
				if (SSID != null
						&& (wifistate == WifiState._wifi_enable
								|| wifistate == WifiState._wifi_disabled
								|| wifistate == WifiState._wifi_unknown || wifistate == WifiState._wifi_null))
					// 获取wifi ssid
					mWifiChangeCallBack.WifiChanged(SSID);

				mWifiChangeCallBack.WifiStateChanged(wifistate);

				mWifiChangeCallBack.WifiChanged();
			}
		}
	};

	/**
	 * 获取wifi ssid
	 * 
	 * @return
	 */
	public String getSSID() {
		return SSID == null ? "" : SSID;
	}
}
